// pages/feedback/index.js
import { request } from "../../request/index.js";
import regeneratorRuntime from "../../lib/runtime/runtime";

Page({

  data: {
    tabs: [
      {
        id: 0,
        value: "体验问题",
        isActive: true
      },
      {
        id: 1,
        value: "商品/商家投诉",
        isActive: false
      }
    ],
    // 被选中的图片路径
    chooseImgs: [],
    // 文本域内容
    textVal: ""
  },
  // 外网图片路径数组
  uploadImgs: []
  ,
  handleTabsItemChange(e) {
    const { index } = e.detail
    let { tabs } = this.data
    tabs.forEach((v, i) => i===index?v.isActive=true:v.isActive=false)
    this.setData({ tabs })
  },
  handleImg() {
    wx.chooseImage({
      count: 5,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (result) => {
        this.setData({
          chooseImgs: [...this.data.chooseImgs, ...result.tempFilePaths]
        })
      }
    })
      
  },
  handleImgRemove(e) {
    const { index } = e.currentTarget.dataset
    let { chooseImgs } = this.data
    chooseImgs.splice(index, 1)
    this.setData({ chooseImgs })
  },
  handleTextInput(e) {
    this.setData({ textVal: e.detail.value })
  },
  handleFormSubmit() {
    
    const { textVal, chooseImgs } = this.data
    if(!textVal.trim()) {
      wx.showToast({
        title: '输入不能为空',
        icon: 'none',
        mask: true
      })
      return
    }
    if(this.data.chooseImgs.length===0) {
      wx.showToast({
        title: '图片不能为空',
        icon: 'none',
        mask: true
      })
      return
    }

    // const params = {
    //   image: '',
    //   apiType: 'this',
    //   token: '0f3bb5e29adf2bafc4d2fbb69cf5'
    // }
    // api不支持多个文件上传
    chooseImgs.forEach((v, i) => {
      wx.uploadFile({
        // 新浪图床
        url: 'https://images.ac.cn/Home/Index/UploadAction/',
        filePath: v,
        // 上传文件的名称，后台用于获取
        name: 'smfile',
        // 顺带文件信息
        formData: {
          smfile: 'test'
        },
        success: (result) => {
          // console.log(result)
          // let url = JSON.parse(result.data).url
          // this.uploadImgs.push(url)

          // 最后一张图片上传完毕
          // todo

          if(i===chooseImgs.length-1) {
            // 将url提交给后台
            this.setData({  
              textVal: '',
              chooseImgs: []
            })
            wx.navigateBack({
              delta: 1
            })
          }
        }
      })  
    })
    wx.navigateBack({
      delta: 1
    })
    
  }
})